package com.spring.aop;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 事务管理器
 */
public class TransactionManager {

    private TransactionManager() {
    }

    private Connection connection;
    private static TransactionManager transactionManager;

    /**
     * 单例 懒汉模式
     * @return
     */
    public static TransactionManager getInstance() {
        if (transactionManager == null) {
            transactionManager = new TransactionManager();
        }
        return transactionManager;
    }

    public void setConnection(Connection connection) {
        this.connection = connection;
    }

    /**
     * 开启事务
     */
    public void OpenTheTransaction() {
        System.out.println("开启事务");
        System.out.println(connection);
        try {
            connection.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 事务提交
     */
    public void commitTransaction(){
        System.out.println("事务提交");
        System.out.println(connection);
        try {
            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    /**
     * 事务回滚
     */
    public void rollback(){
        System.out.println("事务回滚");
        System.out.println(connection);
        try {
            connection.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
